/**
 * 所有版权归 广西梧州 陈锦韬 所有
 *
 * @Title: AuthFilter
 * @Package com.rx.zuul.filter
 * @Description: 权限过滤器
 * @author: 陈锦韬
 * @date: 2021\6\24 0024
 * @version V1.0
 * @Copyright: 2021 陈锦韬  All rights reserved.
 */
package com.rx.zuul.filter;

import com.alibaba.fastjson.JSON;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.rx.core.base.RxBaseConstant;
import com.rx.core.util.RxUtil;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.OAuth2Request;

import java.util.*;

/**
 * @author: Administrator
 * @Description: 权限过滤器
 * @date: 2021\6\24 0024
 */
public class AuthFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        // 最优先
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        // 安全上下文。
        RequestContext context = RequestContext.getCurrentContext();

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (!(authentication instanceof OAuth2Authentication)){
            // 无token 访问
            return null;
        }
        // 获取当前用户信息
        OAuth2Authentication oAuth2Authentication = (OAuth2Authentication)authentication;
        Authentication userAuthentication = oAuth2Authentication.getUserAuthentication();
        if (null == userAuthentication){
            // 无token 访问
            return null;
        }
        Object principal = userAuthentication.getPrincipal();

        // 取出用户权限
        List<String> authList = new ArrayList<>();
        Collection<? extends GrantedAuthority> authorities = userAuthentication.getAuthorities();
        authorities.forEach(e->authList.add(e.getAuthority()));

        OAuth2Request oAuth2Request = oAuth2Authentication.getOAuth2Request();
        Map<String, String> requestParameters = oAuth2Request.getRequestParameters();
        Map<String,Object> jsonToken = new HashMap<>(requestParameters);

        jsonToken.put("principal",principal);
        jsonToken.put("authList",authList);
        // 放在heander 转发给微服务
        context.addZuulRequestHeader(RxBaseConstant.HEARER_JSON_TOKEN, RxUtil.EncryptUtil.encodeUTF8StringBase64(JSON.toJSONString(jsonToken)));
        return null;
    }
}
